Ualign: pushing the limit of template-free retrosynthesis prediction with unsupervised SMILES alignment

Motivation Retrosynthesis planning poses a formidable challenge in the organic chemical industry, particularly in pharmaceuticals. Single-step retrosynthesis prediction, a crucial step in the planning process, has witnessed a surge in interest in recent years due to advancements in AI for science. Various deep learning-based methods have been proposed for this task in recent years, incorporating diverse levels of additional chemical knowledge dependency. Results This paper introduces UAlign, a template-free graph-to-sequence pipeline for retrosynthesis prediction. By combining graph neural networks and Transformers, our method can more effectively leverage the inherent graph structure of molecules. Based on the fact that the majority of molecule structures remain unchanged during a chemical reaction, we propose a simple yet effective SMILES alignment technique to facilitate the reuse of unchanged structures for reactant generation. Extensive experiments show that our method substantially outperforms state-of-the-art template-free and semi-template-based approaches. Importantly, our template-free method achieves effectiveness comparable to, or even surpasses, established powerful template-based methods. Scientific contribution We present a novel graph-to-sequence template-free retrosynthesis prediction pipeline that overcomes the limitations of Transformer-based methods in molecular representation learning and insufficient utilization of chemical information. We propose an unsupervised learning mechanism for establishing product-atom correspondence with reactant SMILES tokens, achieving even better results than supervised SMILES alignment methods. Extensive experiments demonstrate that UAlign significantly outperforms state-of-the-art template-free methods and rivals or surpasses template-based approaches, with up to 5% (top-5) and 5.4% (top-10) increased accuracy over the strongest baseline. Supplementary Information The online version contains supplementary material available at 10.1186/s13321-024-00877-2.


Introduction
Retrosynthesis prediction is a crucial task in organic chemistry, aiding in finding efficient synthetic pathways from target molecules to accessible starting materials.Despite significant advancements in chemical synthesis technology, it still remains a challenge in industries like pharmaceuticals.The extensive search space and the incomplete understanding of chemical reaction mechanisms make retrosynthesis prediction difficult, even for experienced chemists.To address this issue, computer-assisted synthetic planning (CASP) has gained increasing attention in recent years, starting from the seminal work by Corey.This paper focuses on single-step retrosynthesis prediction, which is the fundamental step in CASP.It aims to predict the reactants that can lead to a given product molecule through a single reaction step.
Various deep-learning-based single-step retrosynthesis prediction methods have been proposed in recent years.These methods can be broadly classified into three groups based on their dependency on additional chemical knowledge: template-based, semi-template-based and template-free methods.Template-based methods [5,7,9,37] require an extra database of reaction templates.They frame the retrosynthesis prediction as a classification or retrieval problem for reaction templates suitable for the given product molecule to be synthesized.Among these solutions, Retrosim [7] utilizes molecular similarity to rank reaction templates; LocalRetro [5] and GLN [9] use graph neural networks to model the relationship between reaction templates and molecules to predict the most suitable reaction template; RetroKNN [37] further improves upon LocalRetro by addressing the issue of data imbalance using K-nearest neighbors (KNN).Template-based methods have strong interpretability and can accurately predict reactants.However, these methods are often unable to cover all cases and suffer from poor scalability due to limitations imposed by the template database.
To overcome the limitations faced by template-based methods, researchers have turned to generative models.Semi-template-based methods incorporate chemical knowledge into generative models with the help of chemical toolkits like RDKit [16], breaking free from the limitations imposed by reaction templates.The key idea of most semi-template-based methods [6,26,27,35,38] is to first convert the product into synthons based on reaction center identification and then complete the synthons into reactants.Graph neural networks are commonly used for synthon prediction, followed by leaving group attachment [6,27], conditional graph generation [26], or SMILES generation [38] for reactant completion.Apart from all above, RetroPrime [35] utilizes two independent Transformers to accomplish synthon prediction and reactant generation as separate tasks.
Semi-template-based methods to a certain extent are more in line with chemical intuition.However, these methods increase the complexity of inference and training as they break down retrosynthesis into two subtasks.Failures in synthon prediction directly affect subsequent reactant completion and overall performance.Besides, methods based on leaving group necessitates an extra leaving group database.This requirement, akin to template-based approaches, imposes limitations on the model's scalability.
As generative models, Template-free methods opt to generate reactants directly from the given products.In comparison to generating graph structures, SMILES provides a way to represent molecules as strings.Taking advantage of this, most template-free methods [15,25,28,34,42] use Transformer models to translate between product SMILES and reactants SMILES.In particular, Graph2SMILES [29] replaces the Transformer encoder with a graph neural network, resulting in a permutation-invariant pipeline.There are also methods [21,40] formulates the generation of reactants as a series of graph generation or editing operation and solve it auto-regressively.Existing template-free methods generally follows an auto-regressive generation strategy and use beam search for the generation process.Consequently, preserving a level of diversity in the resultant outputs has emerged as a critical consideration for template-free methods [33].Due to the use of SMILES as input and output, most of template-free methods often overlook the rich topological and chemical bond information present in molecular graphs.Moreover, as reactants molecules need to be generated from scratch, template-free methods frequently suffer from validity issues and fail to leverage an important property of retrosynthesis prediction, i.e., the presence of many common substructures between products and reactants.
In this paper, we focus on the template-free generative approach for retrosynthesis prediction.Existing sequence-to-sequence methods have limitations in extracting robust molecular representations.They overlook the abundance of topological information and chemical bonds, and lack the ability to utilize atom descriptors as rich as those in graph-based methods.Furthermore, template-free methods overlook the fact that the molecular graph topology remains largely unaltered from reactants to products during chemical reactions, as they generate reactants from scratch.While there are methods that attempt to solve this problem using supervised SMILES alignment, they require complex data annotation and impact model training.Given these limitations, the following question naturally arises: Can we effectively leverage the structural information of product molecules using a much simpler approach?To address these issues and further enhance template-free methods, we propose a novel graph-to-sequence pipeline called UAlign.Our approach employs a specifically designed graph neural network as an encoder, incorporating information from chemical bonds during message passing to create more powerful embeddings for the decoder.We introduce an unsupervised SMILES alignment mechanism that establishes associations between product atoms and reactant SMILES tokens which reduces the complexity of SMILES generation and enables the model to focus on learning chemical knowledge.Our model outperforms existing template-free methods by a large margin and demonstrates comparable performance against template-based methods.

Methods
We introduce UAlign, a novel single-step retrosynthesis prediction model based on an encoder-decoder architecture, as demonstrated in Fig. 1.It's a fully templatefree method without any molecule editing operation using RDKit [16].We propose a specially designed variant of Graph Attention Network, which incorporates the information of chemical bonds to enhance the capability of capturing the structural characteristics of molecules.

Preliminary
A molecule can be represented as a graph, denoted by G = (V, E), where V represents the atoms and E represents the chemical bonds.The SMILES representation of a molecule can be obtained by performing a depth-first search (DFS) starting from any arbitrary atom in the molecule graph.Given a molecule graph G = (V, E), we can generate multiple DFS orders and each DFS order corresponds to a SMILES representation of the graph.Denoted the set of all possible DFS orders as D(V ) ⊆ P(V ), P(V ) represents all permutations of the set of atoms V .For each DFS order O ∈ D(V ), we denoted its corresponding SMILES as Smiles(G, O), which lists all atoms in the order dictated by O.To facilitate our subsequent elaboration, we refer to the position of an atom a in the order O as its rank, denoted as rank(a, O).The atom with the minimal rank given order O is then defined as the root atom, denoted as root(G, O).

EGAT +
Chemical bonds play a significant role in determining the properties of molecules and contain valuable information.Previous studies [12,20,39] have demonstrated that incorporating edge information into graph neural networks can greatly enhance their ability to represent molecular structures.To fully leverage the information brought by chemical bonds, we propose a modified version of the Graph Attention Network (GAT) [32] called EGAT + .
Our proposed model explicitly incorporates edge features, which represent the information derived from chemical bonds, into the message passing process.During each iteration of message passing, the EGAT + applies self-attention to each node and its one-hop neighbors to calculate attention coefficient according to both node features and edge features.It then aggregates the both node and edge features of these neighbors, considering the attention coefficients, to update the node features.Denote the node feature of atom u as h  written as ẽ(k) where FFN (k) m , FFN (k)   e and FFN (k)  n are three different feed forward networks, a is a learnable parameter, N (u) denotes the one-hop neighbors of node u and ∥ denotes the concatenation operation.Since there are no chemical bonds with the same beginning and ending atoms, the e (k) u,u is also set as a learnable parameter shared among all atoms.The residual connection and layer normalization [2] are applied to prevent over-smoothing while enlarging the receptive field of the model [36].
The initial node features h u and edge features e u,v are determined via several chemical property descriptors, whose details are shown in Supplementary Sec. 6.After K iterations of message passing, we can obtain the encoded features h (K) u of all atoms and make up the output H ∈ R VP ×d of the encoder, where d denotes the embedding size.

SMILES Alignment
For single-step retrosynthesis prediction, a significant proportion of structures are shared between product molecules and reactant molecules [34,43].However, SMILESbased methods often have to generate the reactant SMILES from scratch, even if most of the structures of reactants are the same as those of the products.This results in the underutilization of input information and becomes the bottleneck of template-free retrosynthesis prediction methods.There are methods [25,34] addressing this issue through supervised SMILES alignment, which involves adding supervised information to establish the correspondence between input and output tokens through crossattention over the input and predicted tokens.This supervised training approach not only requires complex data annotation algorithms but also limits the diversity of the model's attention map, thereby further affecting the model's performance.To address the above-mentioned issues, we propose the unsupervised SMILES alignment method as follows.
Assuming we can identify the location of each product atom in the reactants' SMILES and provide it to the model, a natural correspondence can be established between the input and output atoms.However, during the inference process, revealing this information would lead to label leakage, which is not permitted.Therefore, we propose the following modification: when providing an order of product atoms, we expect the model to generate atom tokens in the reactants' SMILES in this given order as closely as possible.By doing so, we can establish a correspondence between the product atoms and the reactants' SMILES tokens using unsupervised methods without leaking any labels.We refer to this type of reactants' SMILES, which aims to preserve the given order of atom tokens as much as possible, as order-preserving reactant SMILES.Note that SMILES represents atoms in a molecule according to a certain DFS order, the provided order should also be a DFS order for the product molecule.
The generation of order-preserving reactant SMILES will be introduced as follows.Given the product molecule P = (V P , E P ) with a DFS order O P ∈ D(V P ) and the corresponding set of reactant molecules ) that has a nearly consistent atomic appearance sequence with O P as the product and reactants have similar structures.For convenience, we name such a order as O P -corresponding order Product Reactants DFS order Order-Preserving Reactant SMILES .Fig. 2 An example of the process to generate order-preserving reactants SMILES.The atom mapping numbers shown on the figure are included only for clearer explanation and will be removed in our implementation to prevent any label leakage.
of R and denote it as CO(R, O P ).Mathematically, it's defined as where the value of inv(i, j, O P , o) equals 1 if and only if rank(i, O P ) < rank(j, O P ) and rank(i, o) > rank(j, o), and equals 0 otherwise.We sort the reactants R according to rank(root(R, CO(R, O P )), O P ) in ascending order.Then we generate SMILES for each reactant molecule using its O P -corresponding order and join them together using "." to obtain order-preserving reactant SMILES.
For further discussion, we denote the order-preserving reactant SMILES given the reactant molecules R and a DFS order O of product as OP Smiles(R, O).An example of the process to generate order-preserving reactants SMILES is shown in Fig. 2. The detailed implementations are presented in Supplementary Sec.5.1.

Decoder
The decoder takes the node features H ∈ R VP ×d that are generated from the encoder, as well as the given DFS order O P for the product molecule graph as input.We use the vanilla Transformer decoder [31] as our decoder.As mentioned in Sec.2.3, the order information of product atoms are required for SMILES alignment.However, the Transformer decoder is permutation-invariant to memory [17,29], meaning it is not sensitive to the order of the features from encoder.This implies that directly performing cross-attention over H may not effectively capture the relationship between product atoms and reactant SMILES tokens.To address this problem, we introduce position encoding to the node features based on the rank of each atom in the given DFS order O P to generate order-aware node features Ĥ.Then given an input embedding sequence Z ∈ R m×d , the Transformer decoder layer utilizes the order-aware node features as keys and values in all the cross-attention layers.This process ultimately generates the decoded embeddings Ẑ ∈ R m×d .These embeddings are then fed into feed-forward layers FFN 1 : R d → R T to predict the tokens T that should be generated.In summary, the decoder can be mathematically expressed as (3)

Two stage training
There is a significant distribution shift between graphs and SMILES representations.Moreover, our model is specifically designed to generate non-canonical SMILES, which may contain more complex patterns compared to canonical SMILES.To achieve this goal, we propose a two-stage training strategy in this paper.The first stage aims to align the distributions between two distinct modalities: SMILES and molecular graphs, Once the first stage training converges, we proceed to the second stage, which focuses on retrosynthesis prediction.In this stage, the model is trained using the order-preserving reactant SMILES as targets.Given a product molecule graph P , a possible DFS order O P , and a set of reactants R, the model is expected to generate OP Smiles(R, O P ).

Data Augmentation
Different from those Transformer-based methods [25,28,34] taking SMILES as input and canonical SMILES as target, our method takes a graph as input and is trained with non-canonical SMILES.That means the previous SMILES augmentation tricks are not suitable for us.Similar to [34], we choose to augment the training data on-the-fly.
For the first stage, at each iteration, for each molecule M = (V M , E M ), we have a 50% chance of using a random DFS order O M as the input for the model, and using the corresponding Smiles(M, O M ) as the training target.For the other 50%, we randomly select another molecule , and find the DFS order O M that can generate canonical SMILES for M .M and O M are then fed into the model and the target is set as the canonical SMILES of M .Such an augmentation method enables the model to output the atom tokens according to the given DFS order and be aware of different components within a graph.
For the second stage, at each iteration, for each product molecule P = (V P , E P ), we have a 50% probability of using a random DFS order as input, and for the remaining part, we use the DFS order capable of producing canonical SMILES for product as input.The target used for training is the order-preserving reactant SMILES generated based on the input DFS order.This data augmentation method allows the model to focus more on the DFS order for canonical product SMILES while also noticing the correspondence between product atoms and the output SMILES tokens.

Loss
Both stage of training can considered as a kind of translation between graphs and SMILES, thus we use the loss widely used for auto-regressive language generation models for training.Denote the training target as T = {t 1 , t 2 , . . ., t n } and the output of the model T = { t1 , t2 , . . ., tn }, the loss can be written as where l cls (•) is the classification loss.

Results and Discussion
In this section, we conduct extensive experiments to make a comprehensive evaluation of our proposed UAlign.

Evaluation Protocol
Benchmark Datasets.We adopt three datasets for evaluation: (1) USPTO-50K consists of 50,016 atom-mapped reactions grouped into 10 different classes; (2) USPTO-FULL comprises 1,013,118 atom-mapped reactions without any reaction class information.(3) USPTO-MIT consists of 479,035 atom-mapped reactions without any reaction class information.To ensure a fair comparison, we adopt the same training/validation/test splits as those in a previous study [9] for USPTO-50K and USPTO-FULL datasets.The training/validation/test splits is aligned with the previous study [14].The detailed data processing procedure and the statistical information of the processed dataset are presented in Supplementary Sec. 2.
Metrics.We utilize the following three evaluation metrics for evaluation: top-k accuracy, top-k SMILES validity, and top-k round-trip accuracy.The detailed definitions for three metrics are provided in Supplementary Sec. 3.

Performance Comparison
Top-k Accuracy.We compare our model with existing single-step retrosynthesis prediction in terms of top-k accuracy on all the datasets.The results are summarized in  It is noteworthy that while template-based approaches have achieved remarkable performance on the USPTO-50K dataset, their reliance on external template libraries has emerged as a constraint as datasets grow in scale and complexity.This dependency leads to a substantial degradation in model performance.In contrast, template-free methods have demonstrated superior versatility and adaptability, qualities that render them especially appropriate for managing large-scale and intricate datasets.
Top-k SMILES Validity.We use vanilla Transformer, RetroPrime, Retroformer and Graph2SMILES as robust baselines to compare the validity of SMILES in our study.SMILES generation models for retrosynthesis tasks often encounter challenges with maintaining SMILES validity.We do not take the methods based on templates or molecule editing as baseline here because the validity of generated SMILES can be guaranteed by the templates or chemical toolkits.Unlike graph-based models, SMILESbased methods need to ensure that the generated content adheres to the parsing rules of SMILES, without leveraging chemical tools such as RDKit.Consequently, SMILESbased approaches are more susceptible to generating invalid SMILES compared to graph-based models.As shown in Table 4, our model demonstrates superior top-1 and top-5 molecule validity compared to other models, even without employing canonical SMILES as our training objective.This improvement could be attributed to the proposed two-stage training strategy and data augmentation, which assist the model in capturing various SMILES patterns effectively.
Top-k Round-Trip Accuracy.To assess the accuracy of our predicted synthesis plans, we utilize the Molecule Transformer [23] as the benchmark reaction prediction model and calculate the top-k round-trip accuracy.We take RetroPrime, Retroformer and Graph2SMILES as our strongv SMILES-based baselines.We also use take graphbased method GraphRetro into comparison.The results are presented in Table 5.The results clearly indicate that our model outperforms all SMILES-based baselines by a considerable extent and even exceeds the well-established graph-based method, GraphRetro.This underscores the efficacy of our unsupervised SMILES alignment mechanism, which enables the model to efficiently leverage substructures from product molecules to construct reactants.This mechanism allows the model to focus more intently on learning reaction mechanisms, thereby yielding more plausible predictive outcomes.In summary, our model has exhibited a robust capacity for generating coherent and efficacious synthesis pathways, specifically tailored for advanced downstream applications such as multi-step retrosynthesis planning.

Ablation Study
We investigate the effects of different components in our proposed pipelines.The result is summarized in Table 6.
Two Stage Training.We eliminate the initial training phase and directly train the model for the retrosynthesis prediction task.As indicated in Table 6, the two-stage training strategy has consistently led to enhancements in all evaluated metrics.This observation implies that the two-stage training strategy effectively enables the model to adeptly learn the intricacies of molecular SMILES representations, thereby yielding higher quality and more plausible retrosynthetic analysis outcomes.Data Augmentation.We remove the data augmentation during the second training stage, which means training solely using the DFS order that can generate canonical SMILES.Table 6 demonstrates a significant decline in model performance across all metrics.This clearly demonstrates that our data augmentation significantly improves the model's performance.
SMILES Alignment.In the training process, we remove all operations related to SMILES alignment.This includes the removal of the position encoding in Eq. 3, where the features H directly served as the input memory for the Transformer decoder.Since we eliminate the input related to the DFS order, the model was no longer trained using order-preserving reactants SMILES as the target but instead switched to canonical SMILES for product.Additionally, in this set of experiments, we remove the first training stage, which aligns the graph and SMILES modalities as the model architecture changes.The results are reported in Table 6, and they show a significant decline in performance compared to our full version, indicating that the proposed SMILES alignment algorithm is crucial for achieving excellent performance.
It is worth noting that even without data augmentation, two-stage training and SMILES alignment, our model still outperforms the vanilla Transformer by a large margin in terms of all metrics reported in the last line of Table 6.This indicates that graph-based molecular representation learning still has advantages over SMILES-based approaches, and our proposed EGAT + can extract effective molecular representations for downstream usage.

Case Study (Visualization of cross-attention mechanism in transformer with UAling)
We randomly select a case from the dataset and showcase the cross-attention map in Fig. 3.The cross-attention map indicates the correlation between reactant tokens and nodes in the input product graph.This map is obtained by averaging the attention coefficient from each attention head.From the figure, it is evident that the predicted tokens successfully locate their corresponding atoms in the product, which contributes to the accurate prediction.The SMILES alignment can also be observed to assist the model in correctly identifying the reaction center.In accordance with the figure, the bond between atom C:11 and N:9 breaks during the transformation into reactants.
Our model effectively notices this occurrence and focus the attention of token t7 on the reaction centers C:11 and N:9.This strategic focusing successfully guides the completion of the reactants, ensuring that the leaving group is correctly attached to the appropriate atoms.Additionally, we note that the attention coefficient at token t14 is concentrated on atoms C:1 and N:9, which are the first atoms of each reactant molecule according to the given DFS order.This further indicates that our model is able to correctly identify the sites where the reaction occurs and accurately cleave the chemical bonds.Moreover, the attention of newly generated structures (i.e., tokens t7 to t13 ) is directed towards atoms C:1, C:11, and O:2, which correspond to the specific synthon they will attach to.This demonstrates that our model is able to generate appropriate functional groups based on the molecular structure information to form the reactants.All the aforementioned results illustrate that our proposed SMILES Product Reactants Fig. 3 Visualization of cross-attention over order-aware node features and the predicted tokens.The number on the y-axis is the map number of atoms in the product.The reactants atoms that not appear in product is colored red in the x-axis.• represents the end token.
alignment method assists the model in comprehending molecular structural information and helps it to focus on learning chemical rules.
To further investigate the impact of the proposed SMILES alignment mechanism on model training, we visualize the cross-attention coefficients of different Transformer decoder layers.The visualization is provided in Supplementary Fig. 1 of Supplementary Information.From Supplementary Fig. 1, we can observe significant variations in the cross-attention across different layers.Additionally, the establishment of correspondence does not occur exclusively at certain layers, such as the first or last layer.This suggests that directly imposing supervised signals on the cross attention coefficient [25,34] for SMILES alignment is not a wise approach, whether applied to all layers or only the last layer.It also verifies our statement in Sec.2.3 that using unsupervised methods for SMILES alignment does not affect the diversity of attention maps and further has a negative impact on model training and performance.This is why our unsupervised SMILES alignment mechanism achieves better results than supervised SMILES alignment.

Case Study (Multi-step Retrosynthetic Pathway Planning)
To explore the suitability of our model for multi-step retrosynthetic pathway planning, we select three distinct molecules as targets for synthetic route design, and the synthesis routes are obtained through iterative calls to our UAlign model, which is trained with the USPTO-FULL dataset.The predicted pathways are summarized in Fig. 4.
The first case study involves Mitapivat, a compound approved for the treatment of hereditary hemolytic anemias in February 2022 [1].Our model successfully predicted (a) Mitapivat Step-1

Rank-1 verified by experts' knowledge
Step the five-step synthetic route reported in [3], with each step consistently ranked within the top-2 predictions.The first step entails an amide coupling reaction, which our model placed at rank 2, yielding the reactants 1-(cyclopropylmethyl)piperazine (compound 2) and 4-(quinoline-8-sulfonamido)benzoic acid (compound 3).Notably, at the initial step, our model also proposed an alternative synthesis method utilizing the Borch Reductive Amination, which was ranked at the first and is consistent with the synthetic route delineated by Saunders et al.Subsequently, for the synthesis of 4-(quinoline-8sulfonamido)benzoic acid, the model precisely executed a functional group protection strategy during the second step and accurately anticipated the subsequent formation of the sulfonamide, effectively deconstructing the target molecule into readily available precursors.For the synthesis of 1-(cyclopropylmethyl)piperazine, the model strategically protected the amine functional group with a tert-butyloxycarbonyl moiety at the outset and, in the ultimate step, prognosticated the N-alkylation reaction with a topranking accuracy.This example illustrates our model's capability to uncover diverse reaction centers in molecular retrosynthetic design and to generate plausible reactant combinations based on these insights.The second case under scrutiny is Pacritinib, an orally bioavailable and isoform selective JAK-2 inhibitor for the treatment of patients with myelofibrosis, which received FDA approval on February 28, 2022 [41].As shown in Figure 4(b), our model successfully delineates a eight-step synthesis, as described in the literature [4], tracing the synthetic pathway from commercially available 5-nitrosalicylaldehyde and 2,6dichloropyrimidine to the final product.The initial step of the reverse synthesis is olefin metathesis, ranking the first in order of likelihood, followed by another rank-2 aromatic substitution of 4-(3-((allyloxy)methyl)phenyl)-2-chloropyrimidine (compound 12) and 3-((allyloxy)methyl)-4-(2-(pyrrolidin-1-yl)ethoxy)aniline (compound 13).Subsequently, synthesis of 4-(3-((allyloxy)methyl)phenyl)-2-chloropyrimidine was correctly identified via continuous allyl substitution and Suzuki cross-coupling reaction as the top and the second choices.The reverse synthesis of 3-((allyloxy)methyl)-4-(2-(pyrrolidin-1yl)ethoxy)aniline was reduction of the nitro group, followed by another allyl substitution.In the final step, the model's highest probability prediction was reduction of the aldehyde group, followed by a nucleophilic substitution.Despite the synthesis route involving a considerable number of steps and encompassing a variety of reaction types, our model successfully and accurately predicted each step within the top-2 choices.This accomplishment signifies the robustness and efficacy of our model in the context of retrosynthetic analysis.
The final case is Daprodustat, the first oral hypoxy-inducing factor prolyl hydroxylase inhibitor (HIF-PHI) for the treatment of renal anemia caused by chronic kidney disease (CKD) [11].This novel compound received approval for market release from the FDA on the 1st of February, 2023 [41].Our model predicted the three-step synthetic route.The first step reports the hydrolysis of ester at rank 3, which is aligned with the route provided by Duffy et al.Although next two steps provided by our method do not exist in the literature, there are all explainable.The synthesis of ethyl (1,3-dicyclohexyl-2,4,6-trioxohexahydropyrimidine-5-carbonyl)glycinate (compound 21) was identified via dehydration condensation of 1,3-dicyclohexyl-2,4,6-trioxohexahydropyrimidine-5carboxylic acid (compound 23) and ethyl glycinate (compound 22) as the top choice, which avoided using toxic ethyl isocyanatoacetate reported in literature.In the final step, the model's highest probability prediction was amidation of ester, resulting in costeffective and readily accessible starting materials.This case demonstrates the robust extrapolative capacity of our model, highlighting its potential to generate synthetic routes that surpass those documented in the literature.

Limitations
This work does not integrate much domain knowledge related to chemical reaction mechanisms in its design, which to some extent, compromises its interpretability.Similarly to most template-free methods, our work also faces challenges in generating diverse results.These aspects will be left for exploration in future works.

Conclusion
We present UAlign, a novel graph-to-sequence pipeline that achieves state-of-the-art performance in the field of template-free methods.Our approach outperforms existing template-free and semi-template-based methods, while achieving comparable results to template-based methods.By utilizing a specially-designed graph neural network as the encoder, our model effectively leverages chemical and structural information from molecule graphs, resulting in powerful embedding for the decoder.Additionally, Our proposed unsupervised SMILES alignment mechanism facilitates the reuse of shared substructures between reactants and products for generation, allowing the model to prioritize chemical knowledge even without complex data annotations.This significantly enhances the performance of the pipeline.In future work, we plan to further explore multi-step retrosynthesis planning using our UAlign as the single-step retrosynthesis prediction backbone.• remove the reactions where different atoms share the same atom map number.
• remove the reactions whose product is consist of a single atom.
• remove the reactions with invalid SMILES.The empty SMILES is considered as invalid SMILES too.• remove the reactions where product contains atoms that do not appear in reactants.
• remove the reactants that all atoms do not appear in the product.USPTO-MIT.The raw data of USPTO-MIT provided by [4].The original dataset contains reactions that have multiple product molecules.And the reagents are put together with reactions.Thus we perform the following steps to make the dataset more suitable for retrosynthesis prediction task.
• remove the reactions whose product is consist of a single atom • remove the reagents from the reactants.We consider the molecules whose atoms have no intersection with the product as reagents.

Evaluation Metrics
Top-k Accuracy.We use the conventional top-k accuracy to evaluate the performance of model.A prediction result is considered as correct if and only if all the reactants are correctly predicted.Top-k SMILES Validity.As SMILES is considered as correct when it can be identified by RDKit [6].The top-k SMILES validity is calculated as Top-k round-trip Accuracy.There may be multiple methods to synthesize a given product.Evaluating the model's performance solely based on top-k accuracy may lead to biased results.Therefore, in addition to top-k accuracy, we also employ top-k round-trip accuracy as an extra metric to evaluate the model's performance.Top-k round-trip accuracy measures the percentage of predicted reactants that can undergo a reaction and yield the given product.To align with our baseline, we use the Molecule Transformer [8] as the forward reaction prediction model.The calculation of top-k round-trip accuracy follows the same approach as described in [9].

Visualization of the Cross-Attention Coefficients
We visualize the cross-attention maps across different transformer decoder layers using the checkpoint trained on the USPTO-50K dataset.The outcomes are depicted in Supplementary Fig. 1.

Generation of Order-Preserving Reactant SMILES
Given a traversal order O P of product P , there might be multiple DFS orders of a reactant molecule that satisfy the condition to be the O P -corresponding order.This is because reactants might contain atoms and substructures that are not present in the final product.Also, directly solving this problems is very difficult.Thus, we use an approximate algorithm, which is shown in Algorithm 1 to generate the corresponding order defined in Eq. 2 given product molecule P , reactant molecule R and a DFS order O P of P , where am(i) represents the atom map number of atom i.

Model Implementation details (Training and Inference)
We implement our model based on Pytorch 1.13 [7] and torch geometric 2.2.0 [2].For model for USPTO-50K, we set the hidden size as 512, encoder layer as 8, decoder layer as 8 and the number of attention heads as 8.For model for USPTO-FULL, we set the hidden size as 768, encoder layer as 8, decoder layer as 8 and the number of attention heads as 12.The dropout ratio for both model is set as 0.1.The highest learning rate of each model as set as 1.25e-4.We slowly increase our learning rate to the highest in the first few epochs and slowly decrease it using exponential decay.The model is trained with Adam optimizer [5].The maximum number of training epochs for both stages is established at 300, and an early stopping strategy is implemented, which terminates the training process if the model fails to demonstrate performance improvement on the validation set for ten consecutive epochs.
It is important to note that a prescribed DFS order may implicitly capture the distribution of reactant sub-groups within the product, which could inadvertently result in information leakage.To mitigate this issue, we employ a DFS order during the inference process that generates a canonical SMILES representation for the product molecule, ensuring a standardized input that precludes information leakage.

Initial Node Features and Edge Features
We use the atom and bond descriptors provided by Open Graph Benchmark [3].There are nine atom descriptors including atomic number, chirality, formal charge and other properties that can be calculated by RDKit [6].And three bond descriptors are used, containing bond type, bond stereochemistry as well as whether the bond is conjugated.

u
and the edge feature between atom u and v as e

Fig. 1
Fig.1Overview of UAlign: Given a product molecule graph P and one of its DFS order O P , the graph is first fed into the graph neural network called EGAT + to obtain node features H. Then the positional encoding is added to H according to the given DFS order O P to generate the order-aware node features Ĥ. Finally the decoder takes Ĥ as input and generate the SMILES of reactants autoregressively.
while enabling the model to learn the patterns of non-canonical SMILES.Given a molecule graph M and one of its possible DFS orders O M , the training task is to translate the graph into the corresponding SMILES representation based on the given order O M .In detail, this is reached by training the model to generate Smiles(M, O M ) given molecule M and DFS order O M .

Fig. 4
Fig. 4 Multistep retrosynthesis predictions by our method.(a) Mitapivat (b) Pacritinib citrate (c) Daprodust.The reaction centers and leaving groups are highlighted in different colors.The pathway pf molecule (a) and (b) come from literature, while the last one is verified by chemical experts.
molecule graph D(V P ), D(V R ) the set of all possible DFS order for product molecule graph / a single reactant molecule graph O P , O R a DFS order of product, a DFS order of reactant molecule graphs CO(R, O P ) the DFS order of reactant R that has a nearly consistent atomic appearance sequence with O P OP Smiles(R, O P ) the order-preserving reactants SMILES of R based on DFS order O P h (k) u the node feature of node u at k-th iteration of message passing.e (k) u,v the edge feature of edge between node u and v at k-th iteration of message passing.H the output of the encoder, i.e. the encoded node features Z the input token embedding for Transformer decoder Ĥ the order-aware node features Ẑ the output token embedding of Transformer decoder T the predicted token logits list ti the i-th token logits in the predicted token list T the ground truth token list t i the i-th ground truth token

1 (
SMILES is valid), where N is the number of evaluated samples.

Table 1
Top-k accuracy for retrosynthesis prediction on USPTO-50K.* indicates the model with SMILES augmentation.For comparison purpose, the Aug. Transformer is evaluated without the test augmentation.Best performance of each model type is in bold.

Table 2
Top-k accuracy for retrosynthesis prediction on USPTO-MIT.Best performance of each model type is in bold.

Table 1 ,
Table2and Table3.On the USPTO-50K dataset, our model achieves a top-3 accuracy of 77.6%, top-5 accuracy of 84.6% and top-10 accuracy of 90.3% under the reaction class unknown setting, surpassing the SOTA template-free method by 3.5%, 4.0% and 4.7% respectively.And with reaction class given on USPTO-50K dataset, our model achieves the top-1 accuracy of 66.2%, top-5 accuracy of 91.9% and top-10 accuracy of 95.1%, which exceeds the SOTA template-free method by 2.2%, 4.4% and 4.9% respectively.Moreover, our model outperforms all the semi-template-based methods with a noticeable margin.It's also encouraging to see that our method, as a

Table 3
Top-k accuracy for retrosynthesis prediction on USPTO-FULL.* indicates the model with SMILES augmentation.Best performance of each model type is in bold.

Table 5
Top-k round-trip accuracy for retrosynthesis prediction on USPTO-50K with reaction class unknown.

Table 6
Effects of different modules on retrosynthesis performance in reaction class unknown setting of USPTO-50K dataset.Best performance is in bold.

Table 2 .
• remove the reactions with multiple product molecules.The statistical information of the datasets used in this work is summarized in Supplementary Supplementary

Table 2 :
Summary of datasets used in this paper.#Train/#Valid/#Test denotes the number of samples in the training/validation/test set, respectively.#Total is the sum of #Train, #Valid and #Test.